<?php

namespace addons\groupon\model;

use app\admin\model\Admin;
use think\Model;
use addons\groupon\exception\Exception;

/**
 * 自提点申请
 */
class UserSalespersonApplyModel extends Model
{
    // 表名,不含前缀
    protected $name = 'user_salesperson_apply';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $hidden = [];

    protected $append = [
        'status_name',
    ];


    /**
     * 自提点申请详情
     *
     * @return object
     */
    public static function info()
    {
        $user = User::info();

        // 查询审核未通过的或者驳回的自提点申请信息
        $apply = self::where('user_id', $user->id)->where('status', 'in', [-1, 0])->find();

        return $apply;
    }


    /**
     * 自提点申请
     */
    public static function apply($params)
    {
        $user       = User::info();
        $adminModel = new Admin();
        $area       = Area::get($params['area_id']);
        $city       = Area::get($area->pid);
        $province   = Area::get($city->pid);
        $adminModel = new Admin();
        $adminInfo  = $adminModel->where(['city' => $city->name, 'area' => $area->name])->find();
        if (!$adminInfo) {
            new Exception('该区域运营商不存在'.$city->name.'-'.$area->name);
        }
        $params['admin_id']      = $adminInfo['id'];
        $params['user_id']       = $user->id;
        $params['province_name'] = $province->name;
        $params['city_name']     = $city->name;
        $params['area_name']     = $area->name;
        $apply                   = new self();
        $apply->allowField(true)->save($params);

        return $apply;
    }


    /* -------------------------- 访问器 ------------------------ */
    public function getStatusNameAttr($value, $data)
    {
        switch ($data['status']) {
            case -1:
                $status_name = '已拒绝';
                break;
            case 0:
                $status_name = '待审核';
                break;
            case 1:
                $status_name = '已通过';
                break;
            default :
                $status_name = '';
        }

        return $status_name;
    }

}
